#!/usr/bin/python2.7
# -*-  encoding: utf-8 -*-

import os

from addon_manager.addon_config import AddOnConfig, SUPPORTED_VERSION
from addon_manager.addon_exception import UnknownAddonConvention


class AddOnState(object):
    STOPPED = 0  # AddOn 停止
    RUNNING = 1  # AddOn 运行中
    EXCEPTION = 2  # AddOn处于异常状态


class AddOnInfo(object):

    def __init__(self, config, **args):
        """
        name: addon 路径切片名称
        """
        self.__name = args["name"]
        if args.has_key("path"):
            if not os.path.isdir(args["path"]):
                args["path"] = os.path.dirname(args["path"])
            self.__name = args["path"].split("/")[-1]
        self.__inifile = self.__parse_inifile_path(config)
        self.__convention = None
        self.__basedir = self.__parse_basedir(config)
        self.__ini_conf = {"version": "INVALID", "filename": self.__name, "name": self.__name}
        self.__servicepath = self.__parse_service_path(config)
        self.state = AddOnState.EXCEPTION

    def __parse_basedir(self, config):
        inst_dir = config.get_install_dir()
        return os.path.join(inst_dir, self.__name)

    def __parse_inifile_path(self, config):
        """
        通过AddOnConfig中的installDir和AddOn名称拼接获取AddOn配置文件的路径
        """

        # todo：brycen AddOnConfig中增加一个iniconf_name  "addon.config.ini" 不与addonName绑定。
        # todo：这里优先使用"addon.config.ini"，如果找不到，再使用原来的方式。
        inst_dir = config.get_install_dir()
        conf_suffix = config.get_iniconf_suffix()
        conf_name = self.__name + conf_suffix
        return os.path.join(inst_dir, self.__name, conf_name)

    def __parse_service_path(self, config):
        return os.path.join(self.__basedir)

    def __parse_language_type(self):
        return self.__ini_conf.get("languagetype", None)

    def set_convention(self, version):
        if not version in SUPPORTED_VERSION:
            raise UnknownAddonConvention(version)
        self.__convention = version

    def get_convention(self):
        return self.__convention

    def set_iniconf(self, key, value):
        """
        从配置文件中读取到的配置信息
        """
        self.__ini_conf[key] = value

    def __getitem__(self, key):
        if key == "name":
            return self.__name
        elif key == "inifile":
            return self.__inifile
        elif key == "version":
            return self.__convention
        elif key == "basedir":
            return self.__basedir
        elif key == "ini_conf":
            return self.__ini_conf
        else:
            raise KeyError(key)

    def __setitem__(self, key, value):
        raise KeyError(key, value)

    def get_iniconf(self, key=None):
        if key is None:
            return self.__ini_conf
        else:
            return self.__ini_conf.get(key)

    def is_service_enable(self):
        serviceenabled = self.__ini_conf.get("serviceenabled")
        return bool(serviceenabled)

    def get_service_path(self):
        service = self.__ini_conf.get("service")
        if service is None:
            return ""
        return os.path.join(self.__servicepath, service)

    def get_languagetype(self):
        language = self.__ini_conf.get("languagetype")
        return language

    def get_basedir(self):
        return self.__basedir

    def get_port(self):
        return self.__ini_conf.get("portal")

    def get_customprograms_dir(self):
        return os.path.join(self.get_basedir(), "customprograms")

    def __str__(self):
        tmp = """
    name: {},
    inifile: {},
    basedir: {},
    convention: {},
    ini_conf: {}""".format(
            self.__name, self.__inifile, self.__basedir, self.__convention, self.__ini_conf
        )
        return "{" + tmp + "\n}"

    def set_addon_state(self, state):
        self.state = state


__all__ = ["AddOnInfo", "AddOnState"]

if __name__ == "__main__":

    def test_addoninfo():
        addon_info = AddOnInfo(config=AddOnConfig.inst(), **{"name": "hhh"})
        print("addoninfo", addon_info)

    test_addoninfo()
